package com.jabo.douban.demo.presentation.view.activity;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;

import com.jabo.douban.demo.R;
import com.jabo.douban.demo.presentation.viewmodel.SplashActivityViewModel;
import com.jabo.douban.demo.databinding.ActivitySplashBinding;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

/**
 * @anthor JZheng3
 * @Time: 2020/2/26
 */
public class SplashActivity extends BaseActivity {
    private ActivitySplashBinding mViewDataBinding;
    private SplashActivityViewModel mViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mViewDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_splash);
        mViewModel = new ViewModelProvider(this).get(SplashActivityViewModel.class);
        mViewDataBinding.setMActivity(this);
        mViewDataBinding.setMViewModel(mViewModel);
        mViewDataBinding.setLifecycleOwner(this);
        startLogoLayoutAnimator();
        mViewModel.startSkipTime();

        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        hideBottomNaviView();
    }

    private void initData() {
        final String text = mViewDataBinding.btnSkip.getText().toString();
        mViewModel.getSkipSecondLiveData().observe(this, new Observer<Long>() {
            @Override
            public void onChanged(Long integer) {
                mViewDataBinding.btnSkip.setText(text + " " + integer / 1000);
                if (integer == -1) {
                    skipToMain();
                }
            }
        });
    }

    /**
     * 开启logo动画
     */
    private void startLogoLayoutAnimator() {
        mViewDataBinding.btnSkip.post(new Runnable() {
            @Override
            public void run() {
                int adImageHeight = mViewDataBinding.imageViewAd.getHeight();
                int decorViewHeight = getWindow().getDecorView().getHeight();
                int layoutLogoHeight = mViewDataBinding.constraintLayoutLogo.getHeight();
                int layoutLogoBottom = decorViewHeight - mViewDataBinding.constraintLayoutLogo.getBottom();
                int offset = (decorViewHeight - adImageHeight - layoutLogoHeight - 2 * layoutLogoBottom) / 2;
                ObjectAnimator animator = ObjectAnimator.ofFloat(mViewDataBinding.constraintLayoutLogo, "translationY", -offset);
                animator.setDuration(1000);
                animator.start();
            }
        });
    }

    public void skipToMain() {
        mViewModel.cancleTimer();
        Intent starter = new Intent(this, MainActivity.class);
        startActivity(starter);
        finish();
    }

}